package com.example.demo.controller.admin;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.common.CommonResult;
import com.example.demo.common.StatusCode;
import com.example.demo.domain.Admin;
import com.example.demo.dto.AdminLoginDTO;
import com.example.demo.service.AdminService;
import com.example.demo.util.WebUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author liuchao
 * @version 1.0
 * @date 2024/11/5
 */
@RestController("adminAdminController")
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminService adminService;

    @PostMapping(value = "/login")
    public CommonResult<Admin> login(@RequestBody AdminLoginDTO adminLoginDTO) {
       CommonResult<Admin> commonResult = new CommonResult<>();
        QueryWrapper queryWrapper = new QueryWrapper();

        // 查询用户名和密码是否正确
        queryWrapper.eq("admin_name", adminLoginDTO.getUserName());
        String md5Password = SecureUtil.md5(adminLoginDTO.getPassword());
        queryWrapper.eq("password", md5Password);
        Admin admin = adminService.getOne(queryWrapper);

        if (null != admin) {
            // 设置管理员登录名
            admin.setAdmin_name(adminLoginDTO.getUserName());
            // 将管理员信息存储到session中
            WebUtils.getSession().setAttribute("loginAdmin", admin);

            commonResult.setCode(StatusCode.COMMON_SUCCESS.getCode());
            commonResult.setMessage(StatusCode.COMMON_SUCCESS.getMessage());
            commonResult.setData(admin);
        } else {
            commonResult.setCode(StatusCode.COMMON_FAIL.getCode());
            commonResult.setMessage("账号或密码错误");
            commonResult.setData(null);
        }

        return commonResult;
    }

    @GetMapping("/logout")
    public CommonResult<String> logout(){

     CommonResult<String> commonResult = new CommonResult<>();

        //从session中移除loginAdmin属性
        WebUtils.getSession().removeAttribute("loginAdmin");

        //设置返回状态码
        commonResult.setCode(StatusCode.COMMON_SUCCESS.getCode());
        //设置返回消息
        commonResult.setMessage(StatusCode.COMMON_SUCCESS.getMessage());
        //设置返回数据
        commonResult.setData("登出成功!");

        return commonResult;
    }

}
